import { defineStore } from 'pinia'
import { login } from '@/api/auth/index'
import storage from '@/utils/storage'
import router from '@/router'

export const useUserStore = defineStore('user', {
  state: () => ({
    // 认证信息
    token: storage.getLocal('token', ''),
    
    // 用户基本信息
    userInfo: storage.getLocal('userInfo', {}),
    
    // 登录状态
    isLoading: false
  }),

  getters: {
    // 是否已登录
    isLoggedIn: (state) => {
      return !!state.token
    },
    
    // 用户名
    username: (state) => state.userInfo.username || '',
  },

  actions: {
    /**
     * 用户登录
     */
    async login(loginData) {
      try {
        this.isLoading = true
        console.log('开始登录流程:', loginData.username)
        
        // 调用登录API
        const response = await login({
          username: loginData.username,
          password: loginData.password
        })
        
        const { 
          token, 
          username,
          nickname,
          userId,
          tenantId,
          status
        } = response
        
        // 保存认证信息
        this.token = token
        
        // 保存用户基本信息
        this.userInfo = {
          id: userId,
          username: username,
          nickname: nickname,
          status: status
        }
        
        // 持久化存储
        storage.setLocal('token', token)
        storage.setLocal('userInfo', this.userInfo)
        
        console.log('登录成功:', {
          username: username,
          userId: userId,
          tenantId: tenantId,
          status: status
        })
        
        return Promise.resolve(response)
      } catch (error) {
        console.error('登录失败:', error)
        return Promise.reject(error)
      } finally {
        this.isLoading = false
      }
    },

    /**
     * 用户登出
     */
    logout() {
      // 清除所有状态
      this.resetState()
      
      // 重定向到登录页
      router.push('/login')
    },
    
    /**
     * 重置状态
     */
    resetState() {
      this.token = ''
      this.userInfo = {}
      this.isLoading = false
      
      // 清除本地存储
      storage.removeLocal('token')
      storage.removeLocal('userInfo')
    }
  }
})
